Scala Basic

We can execute  a scala program in tow modes
  • Interactive Mode(REPL where REPL stands for Read-Evaluate-Print-Loop.)
  • Script Mode
Interactive Mode
We can start Scala REPL by typing scala command in console/terminal.

First command in scala


The Hello World is the most basic and first program in scala. In scala a basic program consist the following.
  • Object
  • Main Method
  • Statement of Expression
The following code example is a simple scala program.
object ScalaExample{
def main(args:Array[String]){
println ("Hello Scala")
}
}

In the above code, we have created an object ScalaExample. It contains a main method and display message using println method.
  • This file is saved with the name ScalaExample.scala.
  • Command to compile this code is: scalac ScalaExample.scala
  • Command to execute the compiled code is: scala ScalaExample
After executing code it yields the following output.
Hello Scala
You can also use IDE (Integrated Development Environment) for executing scala code.The above example is written using object oriented approach. You can also use functional approach to write code in scala.

Scala Example: Hello Scala

Below is the example by using functional approach.
def scalaExample{
    println("Hello Scala")
}
scalaExample            // Calling of function
Hello Scala

Now, let's take a look at few Syntax related details in Scala:
  • Scala is case-sensitive, which means identifier Scala and scala would have a different meaning in Scala.
  • In Scala, all class names first letter should be in Upper Case. If many words are combined to form a name of the class, each separate word's first letter should be in Upper Case. For example, class MyScalaTutorial.
  • The method names in Scala work slightly differently as compared to class names mainly to distinguish the method names from class names. The method names should start with a Lower Case letter (Source). If multiple words are combined to form the name of the method, then each inner word's first letter should be in Upper Case. For example, def firstScalaTutorial()
  • In Scala, the name of the program file should exactly match the object name. When saving the file, you need to save it using the object name and append .scala to the end of the name. For example, Let's say ScalaTutorial is the object name. Then the file should be saved as ScalaTutorial.scala.
  • Note: If the file name and the object name does not match, then your program will not even compile.
  • Finally, like most programming languages function, Scala program processing also starts from the main() method, which is a crucial part of every Scala Program.

No comments:

Post a Comment